﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace RS232
{
    public partial class Form1 : Form
    {

        private long receive_count = 0;//接收字节计数
        private long send_count = 0;    //发送字节计数
        private StringBuilder sb = new StringBuilder();//字符串构造
        private DateTime current_time = new DateTime();//日期时间变量，用于显示接收数据时间
        private DateTime send_time = new DateTime();//日期时间变量，用于显示发送数据时间

        public Form1()
        {
            InitializeComponent();
            System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;//设置该属性 为false
        }

        private void Form1_Load(object sender, EventArgs e)
        {

            //批量添加波特率列表
            string[] baud = { "43000", "56000", "57600", "115200", "128000", "230400", "256000", "460800" };
            comboBox2.Items.AddRange(baud);

            //设置默认值
            comboBox1.Text = "COM1";
            comboBox2.Text = "115200";
            comboBox3.Text = "8";
            comboBox4.Text = "None";
            comboBox5.Text = "1";

            comboBox1.Items.AddRange(System.IO.Ports.SerialPort.GetPortNames());
        }

        //串口开关按钮
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                //将可能产生异常的代码放置在try块中
                //根据当前串口属性来判断是否打开
                if (serialPort1.IsOpen)
                {
                    //串口已经处于打开状态
                    serialPort1.Close();//关闭串口
                    button1.Text = "打开串口";
                    comboBox1.Enabled = true;
                    comboBox2.Enabled = true;
                    comboBox3.Enabled = true;
                    comboBox4.Enabled = true;
                    comboBox5.Enabled = true;
                    textBox_receive.Text = "";  //清空接收区
                    textBox_send.Text = "";     //清空发送区
                    
                    //状态栏串口状态显示
                    label6.Text = "串口已关闭";
                    label6.ForeColor = Color.Red;
                    button2.Enabled = false;

                }
                else
                {
                    //串口已经处于关闭状态，则设置好串口属性后打开
                    comboBox1.Enabled = false;
                    comboBox2.Enabled = false;
                    comboBox3.Enabled = false;
                    comboBox4.Enabled = false;
                    comboBox5.Enabled = false;
                    serialPort1.PortName = comboBox1.Text;
                    serialPort1.BaudRate = Convert.ToInt32(comboBox2.Text);//波特率
                    serialPort1.DataBits = Convert.ToInt32(comboBox3.Text);//数据位

                    //设置校验位
                    if (comboBox4.Text.Equals("None"))
                        serialPort1.Parity = System.IO.Ports.Parity.  ;
                    else if (comboBox4.Text.Equals("Odd"))
                        serialPort1.Parity = System.IO.Ports.Parity.Odd;
                    else if (comboBox4.Text.Equals("Even"))
                        serialPort1.Parity = System.IO.Ports.Parity.Even;
                    else if (comboBox4.Text.Equals("Mark"))
                        serialPort1.Parity = System.IO.Ports.Parity.Mark;
                    else if (comboBox4.Text.Equals("Space"))
                        serialPort1.Parity = System.IO.Ports.Parity.Space;

                    //设置停止位
                    if (comboBox5.Text.Equals("1"))
                        serialPort1.StopBits = System.IO.Ports.StopBits.One;
                    else if (comboBox5.Text.Equals("1.5"))
                        serialPort1.StopBits = System.IO.Ports.StopBits.OnePointFive;
                    else if (comboBox5.Text.Equals("2"))
                        serialPort1.StopBits = System.IO.Ports.StopBits.Two;

                    serialPort1.Open();//打开串口
                    button1.Text = "关闭串口";
                    button1.BackColor = Color.Firebrick;

                    //状态栏串口状态显示
                    label6.Text = "串口已打开";
                    label6.ForeColor = Color.Green;
                    button2.Enabled = true;
                }
            }
            catch (Exception ex)
            {
                //捕获可能发生的异常并进行处理
                //捕获到异常，创建一个新的对象，之前的不可以再继续使用
                serialPort1 = new System.IO.Ports.SerialPort();
                //刷新COM口选项
                comboBox1.Items.Clear();
                comboBox1.Items.AddRange(System.IO.Ports.SerialPort.GetPortNames());
                //响铃并显示异常给用户
                System.Media.SystemSounds.Beep.Play();
                button1.Text = "打开串口";
                button1.BackColor = Color.ForestGreen;
                MessageBox.Show(ex.Message);
                comboBox1.Enabled = true;
                comboBox2.Enabled = true;
                comboBox3.Enabled = true;
                comboBox4.Enabled = true;
                comboBox5.Enabled = true;
            }
        }

        //发送按钮
        private void button2_Click(object sender, EventArgs e)
        {
            byte[] temp = new byte[1];
            try
            {
                //首先判断串口是否开启
                if (serialPort1.IsOpen)
                {
                    int num = 0;    //获取本次发送字节数

                    send_time = System.DateTime.Now;
                    string sendTimeString = "[SENT " + send_time.ToString("u") + "]";
                    
                    //串口处于开启状态，将发送区文本发送
                    if (radioButton4.Checked)
                    {
                        //以HEX模式发送

                        //首先需要用正则表达式将用户输入字符中的十六进制字符匹配出来
                        string buf = textBox_send.Text;
                        string pattern = @"\s";//匹配包括任何不可见的字符
                        string replacement = "";
                        Regex regex = new Regex(pattern);
                        string send_data = regex.Replace(buf, replacement);

                        //不发送新行
                        num = (send_data.Length - send_data.Length % 2) / 2;

                        //发送时间并显示
                        serialPort1.Write(sendTimeString);
                        textBox_receive.AppendText(sendTimeString);

                        for (int i = 0; i < num; i++)
                        {
                            temp[0] = Convert.ToByte(send_data.Substring(2 * i, 2), 16);
                            serialPort1.Write(temp, 0, 1);//循环发送
                            textBox_receive.AppendText(temp[0].ToString());
                            //textBox_receive.AppendText(send_data.Substring(2 * i, 2), 16));
                        }
                        //如果用户输入的字符是奇数，则单独处理
                        if (send_data.Length % 2 != 0)
                        {
                            temp[0] = Convert.ToByte(send_data.Substring(textBox_send.Text.Length - 1));
                            serialPort1.Write(temp, 0, 1);
                            textBox_receive.AppendText(temp[0].ToString());
                            num++;
                        }
                        //判断是否需要发送新行
                        if (checkBox2.Checked)
                        {
                            //自动发送新行
                            serialPort1.WriteLine("");
                            textBox_receive.AppendText("\r\n");
                            num = textBox_send.Text.Length + 1;//回车占两个字节
                        }
                    }
                    else if(radioButton3.Checked)
                    {
                        //以ASCII模式发送
                        //判断是否需要发送新行
                        if (checkBox2.Checked)
                        {
                            //自动发送新行
                            serialPort1.WriteLine(sendTimeString + textBox_send.Text);
                            textBox_receive.AppendText(sendTimeString + textBox_send.Text+"\r\n");
                            num = textBox_send.Text.Length + 1;//回车占两个字节

                        }
                        else
                        {
                            //不发送新行
                            textBox_receive.AppendText(sendTimeString + textBox_send.Text);
                            serialPort1.Write(sendTimeString + textBox_send.Text);
                            num = textBox_send.Text.Length;
                        }
                    }

                    send_count += num;//计数变量增加
                    label7.Text = "Tx：" + send_count.ToString() + "Bytes";//刷新界面

                }
            }
            catch (Exception ex)
            {
                //捕获到异常，创建一个新的对象，之前的不可以再用
                serialPort1 = new System.IO.Ports.SerialPort();
                //刷新COM口选项
                comboBox1.Items.Clear();
                comboBox1.Items.AddRange(System.IO.Ports.SerialPort.GetPortNames());
                //响铃并显示异常给用户
                System.Media.SystemSounds.Beep.Play();
                button1.Text = "打开串口";
                button1.BackColor = Color.ForestGreen;
                MessageBox.Show(ex.Message);
                comboBox1.Enabled = true;
                comboBox2.Enabled = true;
                comboBox3.Enabled = true;
                comboBox4.Enabled = true;
                comboBox5.Enabled = true;

            }
        }


        private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            //先获取一个字节做判断，如果是发送方的时间，则直接作为ASCII输出，若不是，则做判断后输出
            byte[] first = new byte[1];
            serialPort1.Read(first,0,1);//先读取一个字节做判断
            //如果是接收到时间
            if (Encoding.ASCII.GetString(first) == "[")
            {
                textBox_receive.AppendText(Encoding.ASCII.GetString(first));
                byte[] receive_time = new byte[26];
                serialPort1.Read(receive_time, 0, 26);
                textBox_receive.AppendText(Encoding.ASCII.GetString(receive_time));
                return;

            }

            //如果不是时间，而是数据
            int num = serialPort1.BytesToRead+1;      //获取接收缓冲区的字节数，+1是因为没接收到第一个字节
            byte[] receive_buf = new byte[num];     //声明一个大小为num的字节数据用于存放读出的byte数据
            receive_buf[0] = first[0];
            receive_count += num;   //接收字节计数变量增加num
             

            //分两次读出数据，分别读出时间和接收的字符
            serialPort1.Read(receive_buf, 1, num-1);      //读取接收缓冲区num个字节到byte数组中


            sb.Clear();     //首先清空字符串构造器

            if (radioButton2.Checked)
            {
                foreach(byte b in receive_buf)
                {
                    sb.Append(b.ToString("X2") + ' ');      //将byte型数据转化为2位16进制文本显示，用空格隔开
                }
            }
            else
            {
                //选中ASCII模式显示
                sb.Append(Encoding.ASCII.GetString(receive_buf));//将整个数组解码为ASCII数组
            }
            
            try
            {
                //因为要访问UI资源，所以需要使用invoke方式同步ui
                this.Invoke((EventHandler)(delegate
                {

                    if (checkBox1.Checked)
                    {
                        //显示时间
                        current_time = System.DateTime.Now;     //获取当前时间
                        textBox_receive.AppendText("[RECV " + current_time.ToString("u") + "]" + sb.ToString()+"\r\n");
                    }
                    else
                    {
                        //不显示时间
                        textBox_receive.AppendText(sb.ToString()+"\r\n");
                    }

                    label8.Text = "Rx：" + receive_count.ToString() + "Bytes";
                  
                }
                   )
                );

            }
            catch (Exception ex)
            {
                //响铃并显示异常给用户
                System.Media.SystemSounds.Beep.Play();
                MessageBox.Show(ex.Message);

            }

        }

        private void button3_Click(object sender, EventArgs e)
        {
            textBox_receive.Text = "";      //清空接收文本框
            textBox_send.Text = "";         //清空发送文本框
            receive_count = 0;              //计数清零
            label8.Text = "RX：" + receive_count.ToString() + "Bytes";   //刷新界面
        }

        private void checkBox3_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox2.Checked)
            {
                //自动发送功能选中，开始自动发送
                numericUpDown1.Enabled = false;     //失能时间选择
                timer1.Interval = (int)numericUpDown1.Value;    //定时器赋初值
                timer1.Start();     //启动定时器
                label6.Text = "串口已打开" + "自动发送中...";
            }
            else
            {
                //自动发送功能未选中，停止自动发送
                numericUpDown1.Enabled = true;  //使能时间选择
                timer1.Stop();      //停止定时器
                label6.Text = "串口已打开";
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            button2_Click(button2, new EventArgs());//调用发送按钮回调函数
        }
    }
}
